package com.bluesmart.mia;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class BabyProfileEditActivity extends Fragment implements
		OnClickListener {
	int mSex = 0;
	JSONObject mInfo = null;
	View mView = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.activity_baby_profile_edit,
				container, false);
		mInfo = ((DemoApp) getActivity().getApplicationContext())
				.getSeletedBaby();

		mView.findViewById(R.id.text0).setOnClickListener(this);
		mView.findViewById(R.id.text1).setOnClickListener(this);
		mView.findViewById(R.id.male).setOnClickListener(this);
		mView.findViewById(R.id.female).setOnClickListener(this);

		if(mInfo != null)
		{
			((TextView) mView.findViewById(R.id.text0)).setText(mInfo
					.getString("bexpected"));
			((TextView) mView.findViewById(R.id.text1)).setText(mInfo
					.getString("bday"));
			((TextView) mView.findViewById(R.id.text2)).setText(mInfo
					.getString("nickname"));
			if (mInfo.getString("sex").equals("boy")) {
				mSex = 1;
				((TextView) mView.findViewById(R.id.male))
						.setTextColor(Color.WHITE);
				((TextView) mView.findViewById(R.id.female)).setTextColor(Color
						.parseColor("#32abbe"));
			} else {
				mSex = 2;
				((TextView) mView.findViewById(R.id.female))
						.setTextColor(Color.WHITE);
				((TextView) mView.findViewById(R.id.male)).setTextColor(Color
						.parseColor("#32abbe"));
			}
		}

		return mView;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.right:
			sendHttpRequest();
			break;

		case R.id.camera:
			showImagePicker();
			break;

		case R.id.text0:
			showDate(R.id.text0);
			break;

		case R.id.text1:
			showDate(R.id.text1);
			break;

		case R.id.text3: {
			Intent intent = new Intent(getActivity(),
					AddProfileWeightActivity.class);
			startActivityForResult(intent, 10);
		}
			break;

		case R.id.text4: {
			Intent intent = new Intent(getActivity(),
					AddProfileHeightActivity.class);
			startActivityForResult(intent, 11);
		}
			break;

		case R.id.male:
			mSex = 1;
			((TextView) mView.findViewById(R.id.male))
					.setTextColor(Color.WHITE);
			((TextView) mView.findViewById(R.id.female)).setTextColor(Color
					.parseColor("#32abbe"));
			sendHttpRequest();
			break;

		case R.id.female:
			mSex = 2;
			((TextView) mView.findViewById(R.id.female))
					.setTextColor(Color.WHITE);
			((TextView) mView.findViewById(R.id.male)).setTextColor(Color
					.parseColor("#32abbe"));
			sendHttpRequest();
			break;
		}
	}

	void showImagePicker() {
		final Dialog mDialog = new Dialog(getActivity(),
				R.style.Dialog_Fullscreen);

		OnClickListener listen = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (arg0.getId() == R.id.cancel)
					mDialog.dismiss();
				else if (arg0.getId() == R.id.pic) {
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 3);
				} else {
					mDialog.dismiss();
					Intent intent = new Intent(
							"android.media.action.IMAGE_CAPTURE");
					startActivityForResult(intent, 4);
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.show();

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		if (requestCode == 10) {
			((TextView) mView.findViewById(R.id.text3)).setText(data
					.getStringExtra("value"));
			return;
		}

		if (requestCode == 11) {
			((TextView) mView.findViewById(R.id.text4)).setText(data
					.getStringExtra("value"));
			return;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	void showDate(final int index) {
		Calendar calendar = Calendar.getInstance();

		DatePickerDialog dialog = new DatePickerDialog(getActivity(),
				new DatePickerDialog.OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int month,
							int day) {
						String date = new StringBuilder()
								.append(year)
								.append("-")
								.append((month + 1) < 10 ? "0" + (month + 1)
										: (month + 1)).append("-")
								.append((day < 10) ? "0" + day : day)
								.toString();

						((TextView) mView.findViewById(index)).setText(date);
					}
				}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		dialog.setTitle(getString(R.string.choose_date));
		dialog.show();
	}

	private void sendHttpRequest() {
		String expected = ((TextView) mView.findViewById(R.id.text0)).getText()
				.toString();
		String birth = ((TextView) mView.findViewById(R.id.text1)).getText()
				.toString();
		String nick = ((EditText) mView.findViewById(R.id.text2)).getText()
				.toString();

		MgqDataHandler loginHandler = new MgqDataHandler(getActivity(), true,
				false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					((DemoApp) getActivity().getApplicationContext())
							.sendGetBabyRequest(getActivity());
					ToastUtil.showToastWithOkPic(R.string.success);
				} else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				} else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				} else {
				}
			}
		};

		JSONObject params = new JSONObject();
		params.put("mia_un",
				PreferencesUtils.getString(getActivity(), "username"));
		params.put("pwd", PreferencesUtils.getString(getActivity(), "password"));
		params.put("handType", "updatebaby");
		try {
			params.put("nickname", URLEncoder.encode(nick, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		params.put("sex", mSex == 1 ? "boy" : "girl");
		params.put("bexpected", expected);
		params.put("bday", birth);
		params.put("babyid", mInfo.getString("babyid"));
		MgqRestClient.postBody(
				Constant.SERVER_URL + "/sw/babyInfoHandler.ashx",
				JSON.toJSONString(params), loginHandler);
	}
}
